package com.ycwl.freetv.utils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XmlUtils {

    public static List<Item> parse(InputStream in) throws Exception {
        List<Item> items = new ArrayList<>();
        XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = parserFactory.newPullParser();

        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);

        processParsing(parser, items);

        return items;
    }

    private static void processParsing(XmlPullParser parser, List<Item> items) throws Exception {
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            String eltName = null;

            switch (eventType) {
                case XmlPullParser.START_TAG:
                    eltName = parser.getName();
                    if ("item".equals(eltName)) {
                        Item item = new Item();
                        item.setId(Integer.parseInt(parser.getAttributeValue(0)));
                        items.add(item);
                    }
                    break;
                case XmlPullParser.TEXT:
                    eltName = parser.getName();
                    if ("name".equals(eltName)) {
                        Item item = items.get(items.size() - 1);
                        item.setName(parser.getText());
                    }
                    break;
            }

            eventType = parser.next();
        }
    }

    static class Item {
        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
